package com.dd.config;

import com.github.pagehelper.PageInterceptor;
import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.Configuration;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;

import javax.sql.DataSource;
import java.util.Properties;

public class MyBatisConfig {

    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource) {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        /*配置数据源*/
        sqlSessionFactoryBean.setDataSource(dataSource);

        Configuration configuration = new Configuration();
        /*配置日志*/
        configuration.setLogImpl(StdOutImpl.class);
        /*驼峰命名*/
        configuration.setMapUnderscoreToCamelCase(true);
        /*开启二级缓存*/
        configuration.setCacheEnabled(true);

        //配置分页插件 拦截器
        // 创建PageInterceptor对象，用于分页查询的拦截
        PageInterceptor pageHelper = new PageInterceptor();
        // 创建Properties对象，用于配置PageInterceptor的属性
        Properties properties = new Properties();
        // 设置分页方言为MySQL，以适应MySQL数据库的分页查询
        properties.setProperty("helperDialect", "mysql");
        // 设置是否使用合理模式，合理模式下，如果第一页没有数据，会返回空列表，而不是抛出异常
        properties.setProperty("reasonable", "true");
        // 设置PageInterceptor的属性，包括数据库方言和合理模式
        pageHelper.setProperties(properties);
        // 设置SqlSessionFactoryBean的插件，这里使用PageInterceptor来支持分页查询
        sqlSessionFactoryBean.setPlugins(new Interceptor[]{pageHelper});


        return sqlSessionFactoryBean;
    }

    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        mapperScannerConfigurer.setBasePackage("com.dd.mapper");

        return mapperScannerConfigurer;
    }
}
